'''
获取青龙面板环境变量
'''
import os
import requests


class GetQlEnvs:
    def __init__(self):
        try:
            port = os.environ["QL_PORT"]
            client_id = os.environ["QL_CLIENT_ID"]
            client_secret = os.environ["QL_CLIENT_SECRET"]
            if (port != '' and client_id != '' and client_secret != ''):
                self.qlUrl = "127.0.0.1:" + port
                self.client_id = client_id
                self.client_secret = client_secret
                self.flag = True
                self.getQlToken()
            else:
                print("配置不能为空")
                self.flag = False
        except Exception as e:
            print("config.sh 配置文件缺少配置!")
            self.flag = False

    # 获取青龙token
    def getQlToken(self):
        try:
            res = requests.get("http://"+self.qlUrl+"/open/auth/token?client_id="+self.client_id+"&client_secret="+self.client_secret).json()
            self.qlToken = res['data']['token']
        except Exception:
            print("配置文件有误")
        

    # 获取指定环境变量
    def getCookies(self, key):
        cookies = []
        if (self.flag == False):
            return cookies
        headers = {
            'Authorization': "Bearer " + self.qlToken
        }
        json = requests.get(
            "http://"+self.qlUrl+"/open/envs?searchValue=&t=1673152342396", headers=headers).json()

        if (json['code'] == 200):
            for data in json['data']:
                if (data['status'] == 0 and data['name'] == key):
                    cookies.append(
                        {'cookie': data['value'], 'name': data['remarks']})

        return cookies
